﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.Catalog.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class ManagerController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet, RestoreState]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, PersistState]
        public ActionResult Create(int accountID, string[] flags)
        {
            try
            {
                var m = Svc.ProcessOperation("CreateCatalogManager", new
                {
                    AccountID = accountID,
                    Flags = flags.Merge(",")
                });
                return RedirectToAction(Loc.Act("Edit").Set(new
                {
                    id = JDM.Int32(m.EntityID)
                }));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Create"));
        }

        [HttpGet, RestoreState]
        public ActionResult Edit(int id)
        {
            var m = Svc.ProcessOperation("GetCatalogManager", new
            {
                EntityID = id
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpGet]
        public ActionResult GoTo(int? id, int? accountID, string accountGuid, string accountUsername, string accountEmail)
        {
            if(!id.HasValue)
            {
                dynamic m = null;
                if(accountID.HasValue)
                {
                    m = Svc.ProcessOperation("GetCatalogManagerByAccount", new
                    {
                        AccountID = accountID
                    });
                }
                else if(!String.IsNullOrWhiteSpace(accountGuid))
                {
                    var acc = Svc.ProcessOperation("GetAccountByGuid", new
                    {
                        Guid = accountGuid.ParseAs<Guid>()
                    });
                    if(acc != null)
                    {
                        m = Svc.ProcessOperation("GetCatalogManagerByAccount", new
                        {
                            AccountID = JDM.Int32(acc.EntityID)
                        });
                    }
                }
                else if(!String.IsNullOrWhiteSpace(accountUsername))
                {
                    var acc = Svc.ProcessOperation("GetAccountByUsername", new
                    {
                        Username = accountUsername
                    });
                    if(acc != null)
                    {
                        m = Svc.ProcessOperation("GetCatalogManagerByAccount", new
                        {
                            AccountID = JDM.Int32(acc.EntityID)
                        });
                    }
                }
                else if(!String.IsNullOrWhiteSpace(accountEmail))
                {
                    var acc = Svc.ProcessOperation("GetAccountByEmail", new
                    {
                        Email = accountEmail
                    });
                    if(acc != null)
                    {
                        m = Svc.ProcessOperation("GetCatalogManagerByAccount", new
                        {
                            AccountID = JDM.Int32(acc.EntityID)
                        });
                    }
                }
                if(m == null)
                    return HttpNotFound();
                id = JDM.Int32(m.EntityID);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpPost, PersistState]
        public ActionResult Update(int id, string[] flags)
        {
            try
            {
                Svc.ProcessOperation("UpdateCatalogManager", new
                {
                    EntityID = id,
                    Flags = flags.Merge(",")
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Delete(int id)
        {
            try
            {
                Svc.ProcessOperation("DeleteCatalogManager", new
                {
                    EntityID = id
                });
                return RedirectToAction(Loc.Act("Index"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        #endregion

        #region AJAX Actions

        [HttpPost]
        public ActionResult Grid(int? page, 
            int? rows, 
            string sord, 
            string sidx,
            string searchTerm,
            int? supplierID)
        {
            page = page.HasValue ? page.Value - 1 : 0;
            rows = rows.HasValue ? rows.Value : 30;
            sord = sord.Equals("desc") ? "Descending" : "Ascending";

            var m = Svc.ProcessOperation("SearchCatalogManagers", new 
            {
                Term = new
                {
                    Expression = searchTerm
                },
                SupplierID = supplierID,
                Index = page * rows,
                Count = rows,
                SortBy = new[] 
                {
                    sidx
                },
                SortDir = sord
            }, new
            {
                DisclosureLevel = "Base"
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                data.Add(new[] { 
                    JDM.Int32(i.EntityID),
                    JDM.String(i.Account.Email)
                });
            }

            return Json(new
            {
                pageIndex = page + 1,
                pageCount = Math.Ceiling(JDM.Double(m.TotalCount) / rows),
                totalCount = JDM.Int64(m.TotalCount),
                data = data.ToArray()
            });
        }

        [HttpPost]
        public ActionResult Autocomplete(string term)
        {
            var m = Svc.ProcessOperation("GetCatalogManagerDictionary", new
            {
                Term = new
                {
                    Expression = String.Format("{0}%", term)
                },
                Count = 10
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                data.Add(new
                {
                    id = JDM.String(i.Key),
                    value = JDM.String(i.Value)
                });
            }
            return Json(data.ToArray());
        }

        #endregion
    }
}
